<!-- 后厨原料采购 - 采购单管理 -->
<template>
  <div>
    <cus-search style="padding-bottom: 0;">
      <cus-search-item>
        <Form
          :model="form"
          :label-width="80"
          ref="formValidate"
          @keydown.native.enter.prevent="onInit"
        >
          <FormItem label="创建时间" class="mr_48 mb_20">
            <DatePicker
              type="daterange"
              @on-change="sDateChange"
              ref="formDate"
              placeholder="开始日期 - 结束日期"
              style="width: 200px"
            />
          </FormItem>
          <FormItem
            label="采购计划名称"
            :label-width="110"
            class="mr_48 mb_20"
            prop="purchasingPlanName"
          >
            <Input
              clearable
              v-model="form.purchasingPlanName"
              maxlength="20"
              placeholder="请输入采购计划名称"
            />
          </FormItem>
          <FormItem label="采购来源" class="mr_48 mb_20" prop="formSource">
            <Select
              size="large"
              v-model="form.formSource"
              placeholder="全部"
              clearable
              style="width: 200px"
            >
              <Option
                v-for="item in formSourceTree"
                :value="item.value"
                :key="item.value"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="审核状态" v-if="true" class="mr_48 mb_20" prop="auditState">
            <Select
              size="large"
              v-model="form.auditState"
              placeholder="全部"
              clearable
              style="width: 200px"
            >
              <Option value="0">待提交</Option>
              <Option value="1">已审核</Option>
              <Option value="2">待审核</Option>
              <Option value="3">已驳回</Option>
            </Select>
          </FormItem>
          <cusButton
            class="ml_20 mb_20"
            type="primary"
            @onClick="
              pages.page = 1;
              postApiPurchasingGetAllPurchasingPlanPageApi();
            "
            >查询</cusButton
          >
          <cusButton class="ml_20 mb_20" type="primary" @onClick="reset()"
            >重置</cusButton
          >
        </Form>
      </cus-search-item>
    </cus-search>
    <cus-card :showTitle="false"  class="cardBox mt_20">
      <div class="btnBox">
        <cusButton
          type="primary"
          @onClick="onAdd()"
          style="width: 150px"
          v-permission="20"
          >添加</cusButton
        >
      </div>
      <cusTable
        border
        :loading="form.loading"
        :columns="columns"
        :data="data"
        :size="vuex_config.tableSize"
        :bottomClass="['cus-page']"
      >
        <template slot-scope="{ row, index }" slot="operation">
          <div class="flex">
            <cus-button
              type="text"
              size="small"
              :style="{ color: '#1E6FFF' }"
              style="padding: 0 8px"

              @onClick="onShow(row)"
            >
              <Icon type="ios-search" size="4" style="margin: 2px 5px 0 0" />
              <span>查看</span>
            </cus-button>
            <cus-button
              type="text"
              size="small"
              :style="{ color: '#1E6FFF' }"
              style="padding: 0 8px"
              v-permission="40"
              @onClick="downTableExcel(row)"
            >
              <Icon
                type="ios-download-outline"
                size="4"
                style="margin: 2px 5px 0 0"
              />
              <span>导出</span>
            </cus-button>
            <cus-button
              type="text"
              size="small"
              v-if="row.auditState != 1 && row.auditState != 5"
              :style="{ color: '#1E6FFF' }"
              style="padding: 0 8px"
              @onClick="examineVerifyClick(row)"
            >
              <Icon
                type="ios-cloud-upload-outline"
                size="4"
                style="margin: 2px 5px 0 0"
              />
              <span>{{ row.auditState == 0 ? "上报审核" : "重新上报" }}</span>
            </cus-button>
          </div>
        </template>
      </cusTable>
      <div class="cus_page">
        <cus-page
          :data="pages"
          class="mt_20"
          @pageChange="postApiPurchasingGetAllPurchasingPlanPageApi"
        ></cus-page>
      </div>
    </cus-card>
    <!--添加采购需求-->
    <Modal
      v-model="importModal"
      :title="!Flag ? '导入采购需求' : '添加采购需求'"
      width="480"
      style="z-index: 0"
      @on-visible-change="changeImportModal"
    >
      <Form
        ref="importForm"
        :model="importForm"
        :rules="ruleValidate"
        :label-width="120"
      >
        <FormItem label="采购时间" prop="dateTime" key="1236">
          <el-date-picker
            type="week"
            format="yyyy 第 WW 周"
            placeholder="选择周"
            v-model="importForm.dateTime"
            @change="dateWeekChange"
            transfer
            :append-to-body="true"
            :picker-options="{ firstDayOfWeek: 1 }"
            style="width: 250px; z-index: 9999 !important; position: relative"
          >
          </el-date-picker>
        </FormItem>
        <FormItem label="采购计划名称" prop="materialName">
          <Input
            v-model="importForm.materialName"
            clearable
            style="width: 250px"
            placeholder="选择采购时间自动生成采购计划名称"
          ></Input>
        </FormItem>
        <!-- <FormItem label="选择文件" v-if="!Flag" prop="fileName">
					<Upload
						ref="upload"
						:before-upload="beforeUpload"
						action=""
						multiple
						type="select"
					>
						<Button
							icon="ios-cloud-upload-outline"
							style="
                width: 200px;
                height: 40px;
                display: flex;
                justify-content: left;
                align-items: center;
                overflow: hidden;
              "
							>{{ importForm.fileName || '上传文件' }}</Button
						>
					</Upload>
				</FormItem> -->
        <FormItem label="备注">
          <Input
            v-model="importForm.remark"
            :maxlength="100"
            show-word-limit
            type="textarea"
            :autosize="{ minRows: 8 }"
            placeholder="请输入备注"
            style="width: 250px"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <slot name="footer">
          <div class="modal-footer">
            <cus-button size="small" class="mr_2" @onClick="onCancel"
              >取消</cus-button
            >
            <cus-button type="primary" size="small" @onClick="onOk"
              >确认</cus-button
            >
          </div>
        </slot>
      </div>
    </Modal>
    <!--提交审核-->
    <examineVerify ref="examineVerify"></examineVerify>
  </div>
</template>
<script>
import {
  postApiPurchasingGetAllPurchasingPlanPage,
  postApiPurchasingThisWeekIsExistInPortPurchasingExcel,
  postApiPurchasingInportPurchasingPlanExcel,
  getApiPurchasingDownloadPurchasingSummaryExcel,
  postApiFoodBookServiceAddPurchasingPlan,
  postApiPurchasingPurchasingSummaryPoOrde
} from "@/api/business/manager";
import examineVerify from "./components/examineVerify";

export default {
  components: { examineVerify },
  data() {
    return {
      form: {
        loading: false,
        startDate: "", //开始时间
        stopDate: "", //结束时间
        purchasingPlanName: null, //采购计划名称
        formSource: null, //生活方式
        auditState: "" //审核状态
      },
      //采购需求添加表单
      importForm: {
        dateTime: "",
        startDate: "", //导入采购需求开始时间
        stopDate: "", //导入采购需求结束时间
        materialName: "", //采购计划名称
        file: null, //导入采购需求文件
        fileName: null, //文件名称
        remark: "" //备注
      },
      ruleValidate: {
        dateTime: [
          {
            required: true,
            message: "采购时间不能为空",
            // trigger: "change"
          }
        ],
        materialName: [
          {
            required: true,
            message: "采购计划名称不能为空",
            trigger: "change"
          }
        ],
        fileName: [
          {
            required: true,
            message: "文件不能为空",
            trigger: "change"
          }
        ]
      },
      //生活方式Select数据
      formSourceTree: [
        {
          label: "全部",
          value: ""
        },
        {
          label: "食谱",
          value: "0"
        },
        {
          label: "手工创建",
          value: "1"
        },
        {
          label: "导入",
          value: "2"
        }
      ],
      // 表头
      columns: [
        {
          title: "序号",
          type: "index",
          align: "center",
          width: 70
        },
        {
          title: "采购计划名称",
          key: "name",
          align: "left"
        },
        {
          title: "来源",
          key: "fromSource",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                {},
                params.row.fromSource == 0
                  ? "食谱"
                  : params.row.fromSource == 1
                  ? "手工创建"
                  : "导入"
              )
            ]);
          }
        },
        {
          title: "创建时间",
          key: "createDate",
          align: "center"
        },
        {
          title: "审核状态",
          // key: "auditState",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                {
                  style: {
                    background:
                      params.row.auditState == 0
                        ? "#1E6FFF"
                        : (params.row.auditState == 1 || params.row.auditState == 5)
                        ? "rgb(25, 190, 107)"
                        : params.row.auditState == 2
                        ? "#FF9900"
                        : "#F0402D",
                    color: "#ffffff",
                    padding: "5px"
                  }
                },
                // （0 ：待提交，1：已审核, 2: 待审核, 3: 驳回, 4:手工创建不需显示）
                params.row.auditState == 0
                  ? "待提交"
                  : params.row.auditState == 1
                  ? "已审核"
                  : params.row.auditState == 2
                  ? "待审核"
                  : params.row.auditState == 3
                  ? "已驳回"
                  : params.row.auditState == 4
                  ? "已撤销"
                  : params.row.auditState == 5
                  ? "已自动审核"
                  : ""
              )
            ]);
          }
        },
        {
          title: "备注",
          key: "remark",
          align: "center"
        },
        {
          title: "操作",
          fixed: "right", // 右侧固定
          slot: "operation",
          align: "center",
          width: 245
        }
      ],
      data: [], // 表格列表
      // 分页
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0
      },
      importModal: false, //导入采购需求模态框
      Flag: false // false导入采购需求  true为添加采购需求
    };
  },
  mounted() {
    this.postApiPurchasingGetAllPurchasingPlanPageApi();
  },

  methods: {
    reset() {
      this.$refs["formValidate"].resetFields();
      this.$refs.formDate.handleClear(); //清空时间
    },
    //时间事件
    sDateChange(time) {
      this.form.startDate = time[0];
      this.form.stopDate = time[1];
      this.postApiPurchasingGetAllPurchasingPlanPageApi();
    },
    //生成公式事件
    formSourceOnchange(v) {
      if (v == "全部") {
        this.form.formSource = "";
      } else {
        this.form.formSource = v;
      }
      this.postApiPurchasingGetAllPurchasingPlanPageApi();
    },
    //添加采购需求对话框状态发生改变
    changeImportModal(v) {
     if(!v) this.$refs['importForm'].resetFields()
    },
    //添加采购计划事件
    onAdd() {
      this.importForm.dateTime = "";
      this.importForm.startDate = "";
      this.importForm.stopDate = "";
      this.importForm.materialName = "";
      this.importForm.file = "";
      this.importForm.fileName = "";
      this.importForm.remark = "";
      this.importModal = true;
      this.Flag = true;
    },
    //导入采购需求时间选择事件
    dateWeekChange(time) {
      console.log(this.importForm.dateTime);
      if(time) {
        this.$refs.importForm.validateField('dateTime',valid => '');
      } else {
        this.$refs["importForm"].validateField('dateTime',(error) => {
          valid => error
                })
                return
      }
    
  
      this.importForm.startDate = this.getCurrentWeek(time)[0];
      this.importForm.stopDate = this.getCurrentWeek(time)[6];
      this.importForm.materialName =
        this.getCurrentWeek(time)[0].substring(5) +
        " - " +
        this.getCurrentWeek(time)[6].substring(5) +
        "号采购计划";
      console.log(this.importForm.materialName);
    },
    //导入采购需求Excel文件上传前事件
    beforeUpload(file) {
      this.importForm.file = file;
      this.importForm.fileName = file.name;
      return;
    },
    //导入采购需求模态框确认提交
    onOk() {
      console.log(this.$refs["importForm"]);
      this.$refs["importForm"].validate(valid => {
        if (valid) {
          if ((this.Flag = false)) {
            this.postApiPurchasingThisWeekIsExistInPortPurchasingExcelApi();
          } else {
            this.postApiFoodBookServiceAddPurchasingPlanApi();
          }
        }
      });
    },
    //取消
    onCancel() {
      this.importModal = false;
      this.form.materialName = ""; //采购计划名称
      this.importForm.dateTime = ""; //时间
      this.form.file = ""; //导入采购需求文件
      this.form.remark = ""; //备注
    },
    //下载采购单Excel文件
    downExcel() {
      this.getApiPurchasingDownloadPurchasingSummaryExcelApi();
    },
    //下载Table采购单Excel文件
    downTableExcel(v) {
      if (v.auditState == 3) {
        this.$Message.info("采购单审核不通过,无法导出!");
      } else {
        this.postApiPurchasingPurchasingSummaryPoOrdeApi(v.id);
      }
    },
    //查看(采购单管理)
    onShow(row) {
      this.$router.push({
        name: "采购单查看",
        query: {
          id: row.id, //采购计划id
          status: row.auditState
        }
      });
    },
    // 审核
    examineVerifyClick(row) {
      console.log("=========", row.id);
      this.$refs["examineVerify"].form = this.$cu.deepClone(row);
      this.$refs["examineVerify"].show();
    },
    // 获取本周日期组件处理
    getCurrentWeek(date) {
      let nowData = new Date(date); //传入时间参数,如 2021-11-09 获取给定日期所属的周 日期
      let currentDay = nowData.getDay();
      if (currentDay == 0) {
        currentDay = 7;
      }
      let beforweek = [],
        afterWeek = [];
      for (let i = 1; i <= 7; i++) {
        if (currentDay - i >= 0) {
          let DayTime =
            nowData.getTime() - (currentDay - i) * 24 * 60 * 60 * 1000;
          beforweek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        } else {
          let DayTime = nowData.getTime() + (8 - i) * 24 * 60 * 60 * 1000;
          afterWeek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        }
      }
      afterWeek = afterWeek.reverse();
      let dateList = [...beforweek, ...afterWeek];
      return dateList;
    },
    //采购单查询---------------------------------接口
    postApiPurchasingGetAllPurchasingPlanPageApi() {
      this.form.loading = true;
      return new Promise(resolve => {
        let params = {
          startDate: this.form.startDate, //开始时间
          stopDate: this.form.stopDate, //结束时间
          purchasingPlanName: this.form.purchasingPlanName, //采购计划名称
          formSource: this.form.formSource, //生成方式
          auditState: this.form.auditState, //审核状态
          size: this.pages.pageSize,
          current: this.pages.page
        };
        postApiPurchasingGetAllPurchasingPlanPage(params).then(res => {
          this.form.loading = false;
          if (res.retCode == 2000) {
            this.data = res.data.records;
            this.data.forEach(element => {
              element.createDate = new Date(element.createDate).Format(
                "yyyy-MM-dd hh:mm:ss"
              );
            });
            this.pages.pageTotal = res.data.total;
            resolve();
          }
        });
      });
    },
    //导入采购单Excel文件前效验时间段内是否已导入采购需求------------接口
    postApiPurchasingThisWeekIsExistInPortPurchasingExcelApi() {
      this.$cu.showLoading();
      return new Promise(resolve => {
        let params = {
          purchasingPlanName: this.importForm.materialName, //采购计划名称
          startDate: this.importForm.startDate, //采购计划k开始时间
          stopDate: this.importForm.stopDate //采购计划k结束时间
        };
        postApiPurchasingThisWeekIsExistInPortPurchasingExcel(params).then(
          res => {
            if (res.retCode == 2000) {
              this.postApiPurchasingInportPurchasingPlanExcelApi();
              resolve();
            } else {
              this.$cu.hideLoading();
              this.importModal = false;
            }
          }
        );
      });
    },
    //导入采购单Excel文件----------------------------接口
    postApiPurchasingInportPurchasingPlanExcelApi() {
      return new Promise(resolve => {
        let params = new FormData();
        for (const key in this.importForm) {
          params.append(key, this.importForm[key]);
        }
        postApiPurchasingInportPurchasingPlanExcel(params).then(res => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            this.postApiPurchasingGetAllPurchasingPlanPageApi();
            this.$cu.hideLoading();
            this.importModal = false;
            resolve();
          } else {
            this.$cu.hideLoading();
            this.importModal = false;
          }
        });
      });
    },
    //导出采购单Excel文件----------------------------接口
    getApiPurchasingDownloadPurchasingSummaryExcelApi() {
      this.$cu.showLoading();
      return new Promise(resolve => {
        getApiPurchasingDownloadPurchasingSummaryExcel().then(res => {
          if (res.retCode == 2000) {
            this.$Message.success(res.retMsg);
            window.location.href = res.data;
            this.$cu.hideLoading(2);
            resolve();
          } else {
            this.$cu.hideLoading(2);
          }
        });
      });
    },
    //添加采购单---------------------------------接口
    postApiFoodBookServiceAddPurchasingPlanApi() {
      return new Promise(resolve => {
        let params = {
          name: this.importForm.materialName, //采购计划名称
          startDate: this.importForm.startDate, //采购计划k开始时间
          stopDate: this.importForm.stopDate, //采购计划k结束时间
          remark: this.importForm.remark //备注
        };
        postApiFoodBookServiceAddPurchasingPlan(params).then(res => {
          if (res.retCode == 2000) {
            this.$cu.hideLoading();
            this.$Message.success(res.retMsg);
            this.postApiPurchasingGetAllPurchasingPlanPageApi();
            this.importModal = false;
            resolve();
          } else {
            this.importModal = false;
            this.$cu.hideLoading();
          }
        });
      });
    },
    //导出Tbale表格单个采购计划------------------接口
    postApiPurchasingPurchasingSummaryPoOrdeApi(id) {
      return new Promise(resolve => {
        postApiPurchasingPurchasingSummaryPoOrde({ purchasingPlanId: id }).then(
          res => {
            if (res.retCode == 2000) {
              window.location.href = res.data;
              resolve();
            }
          }
        );
      });
    }
  }
};
</script>

<style lang="less" scoped>
.cardBox {
  box-shadow: 0px 4px 8px 0px rgba(108, 137, 165, 0.18);
}
.btnBox {
  padding-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
